<template>
  <div
    class="search-form-wrapper"
    ref="searchFormWrapperRef"
    v-if="queryList.length > 0"
  >
    <el-form
      :inline="true"
      :model="searchForm"
      layout="inline"
      class="search-form"
    >
      <div
        class="field-item"
        v-for="field of queryList"
        :key="field.formKey"
        @click="handleFieldClick(field)"
      >
        <el-form-item :label="field.label">
          <RenderField
            :field="field"
            allowClear
            v-model="searchForm[field.formKey]"
          />
        </el-form-item>
      </div>
      <div class="btn-wrapper">
        <!-- :style="{ marginBottom: layoutConfig.formItemRowGutter + 'px' }" -->
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { useTableStore } from "@/store/table";
import RenderField from "@/components/RenderField/Element.vue";
import { getFieldDefaultValue } from "@/utils";

const emit = defineEmits(["queryList"]);

const store = useTableStore();
const { queryList, fieldList } = storeToRefs(store);

const searchForm = ref({});
watch(
  () => queryList.value,
  () => {
    resetSearchForm();
  }
);

function handleSearch() {
  emit("queryList", { ...searchForm.value });
}

function handleReset() {
  resetSearchForm();
  handleSearch();
}

function resetSearchForm() {
  for (const query of queryList.value) {
    searchForm.value[query.formKey] = getFieldDefaultValue(query.type);
  }
}
function handleFieldClick(field) {
  store.setCurrentField(
    fieldList.value.find((item) => item.dataIndex === field.formKey)
  );
}
</script>

<style lang="less" scoped>
.search-form {
  display: flex;
  flex-wrap: wrap;
  background: #fff;
  padding: 15px 0;
}
.field-item {
  width: 220px;
  margin-right: 20px;
  :deep(.el-form-item, .el-select) {
    width: 100%;
  }
}
.btn-wrapper {
  //   margin-left: 20px;
}
</style>
